<template>
    <div class="canvas-image">
        fslkadjfl
        <img :src="baseSrc" alt="网图" />
        <canvas
            ref="canvasDom"
            class="my-canvas"
            :width="imgWidth"
            :height="imgHeight"
        ></canvas>
    </div>
</template>
<script setup lang="ts">
import { Ref, ref, watchEffect } from 'vue'
import testImg from '@/assets/images/test.jpg'
const canvasDom = ref<HTMLCanvasElement>()
const baseSrc: Ref<string | undefined> = ref()
const imgSrc = testImg
const imgWidth = ref(400)
const imgHeight = ref(400)
const imgLoaded = ref(false)
const imgObj = new Image()
imgObj.src = imgSrc
imgObj.setAttribute('style', 'width: 100px; height: 100px;')
imgObj.onload = () => {
    imgWidth.value = imgObj.naturalWidth
    imgHeight.value = imgObj.naturalHeight
    imgLoaded.value = true
}
// const borders = [[[0, 0], [10, 20]], [[30, 20], [40, 40]]]
watchEffect(() => {
    if (canvasDom.value && imgLoaded.value) {
        draw()
    }
})
const draw = () => {
    if (!canvasDom.value || !imgLoaded.value) return
    const ctx = canvasDom.value.getContext('2d')
    if (ctx) {
        ctx.drawImage(imgObj, 0, 0)
        ctx.beginPath()
        ctx.moveTo(0, 0)
        ctx.lineTo(10, 0)
        ctx.lineTo(10, 20)
        ctx.lineTo(0, 20)
        ctx.lineTo(0, 0)
        ctx.stroke()
        ctx.beginPath()
        ctx.lineTo(30, 20)
        ctx.lineTo(40, 20)
        ctx.lineTo(40, 40)
        ctx.lineTo(30, 40)
        ctx.lineTo(30, 20)
        ctx.stroke()
        const base = canvasDom.value.toDataURL('image/png')
        baseSrc.value = base
    }
}
</script>
<style lang="scss" scoped>
.canvas-image {
    .my-canvas {
        // width: 100vw;
        // height: 100vh;
        border: 1px solid black;
    }
}
</style>
